package com.zhongwang.business.module.estimateBudgetAccountingManage.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zhongwang.business.common.ImportCallBack;
import com.zhongwang.business.gen.entity.*;
import com.zhongwang.business.module.estimateBudgetAccountingManage.dao.AccountingInfoDao;
import com.zhongwang.business.module.estimateBudgetAccountingManage.model.BusBudgetAccountingBasicInfoConfigModel;
import com.zhongwang.business.module.estimateBudgetAccountingManage.model.BusMaterialDataModel;
import com.zhongwang.business.module.estimateBudgetAccountingManage.model.excelImport.MacHoursExportModel;
import com.zhongwang.business.util.ShiroUtils;
import com.zhongwang.business.util.XYHFileUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 徐一贺
 * @className RawMatImportListener
 * @description 原材料信息导入监听器
 * @date 2020/11/21 14:46
 * @versron ver 1.0
 */
public class MacImportListener extends AnalysisEventListener<MacHoursExportModel> {
    /**
     * 钩子
     */
    private ImportCallBack callBack;
    /**
     * Excel相关参数模型
     */
    private MacHoursExportModel param;
    /**
     * 材料信息数据持久层
     */
    private AccountingInfoDao accountingInfoDao;
    /**
     * 错误列表
     */
    private List<MacHoursExportModel> errorList = new ArrayList<>();
    /**
     * 可用数据列表
     */
    private List<BusMachiningHours> macList = new ArrayList<>();
    /**
     * 当前时间
     */
    private Date currentTime = new Date();

    /**
     * 构造函数
     *
     * @param param             页面参数
     * @param callBack          回调函数
     * @param accountingInfoDao 持久层
     */
    public MacImportListener(MacHoursExportModel param, ImportCallBack callBack, AccountingInfoDao accountingInfoDao) {
        this.callBack = callBack;
        this.param = param;
        this.accountingInfoDao = accountingInfoDao;
    }

    /**
     * 验证
     *
     * @param data 每行数据
     */
    @Override
    public void invoke(MacHoursExportModel data, AnalysisContext context) {
        StringBuffer warningMessage = new StringBuffer();
        BusBudgetAccountingCost cost = accountingInfoDao.getBusBudgetAccountingCostByPrimaryKey(param.getId());
        BusBudgetAccountingTask order = accountingInfoDao.getBusBudgetAccountingTaskModelById(cost.getBatId());
        if (data.getDiagram() != null && !data.getDiagram().equals("")) {
            data.setDiagram(data.getDiagram().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getDiagram() == null) {
            warningMessage.append("请填写图号！\r\n");
        } else if ("".equals(data.getDiagram())) {
            warningMessage.append("请填写图号！\r\n");
        }
        if (data.getDrawingNo() != null && !data.getDrawingNo().equals("")) {
            data.setDrawingNo(data.getDrawingNo().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getDrawingNo() == null) {
            warningMessage.append("请填写图纸名称！\r\n");
        } else if ("".equals(data.getDrawingNo())) {
            warningMessage.append("请填写图纸名称！\r\n");
        }

        if (data.getNum() != null && !data.getNum().equals("")) {
            data.setNum(data.getNum().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getNum() == null) {
            warningMessage.append("请填写数量！\r\n");
        } else if ("".equals(data.getNum())) {
            warningMessage.append("请填写数量！\r\n");
        }
        if (data.getProcess() != null && !data.getProcess().equals("")) {
            data.setProcess(data.getProcess().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getProcess() == null) {
            warningMessage.append("请填写工序！\r\n");
        } else if ("".equals(data.getProcess())) {
            warningMessage.append("请填写工序！\r\n");
        } else {
            VwComProcess process = accountingInfoDao.getVwComProcessByName(data.getProcess());
            if (process == null) {
                warningMessage.append("工序不存在，请填写存在的工序，如不清楚请咨询类似项目机加工艺卡相关制作人！\r\n");
            }
        }
        if (data.getNameType() != null && !data.getNameType().equals("")) {
            data.setNameType(data.getNameType().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getNameType() == null) {
            warningMessage.append("请填写设备类型！\r\n");
        } else if ("".equals(data.getNameType())) {
            warningMessage.append("请填写设备类型！\r\n");
        } else {
            VwEquType equType = accountingInfoDao.getVwEquTypeByName(data.getNameType());
            if (equType == null) {
                warningMessage.append("设备类型不存在，请填写存在的设备类型，如不清楚请咨询类似项目机加工艺卡相关制作人！\r\n");
            }
        }

        if (data.getName() != null && !data.getName().equals("")) {
            data.setName(data.getName().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getName() == null) {
            warningMessage.append("请填写设备型号！\r\n");
        } else if ("".equals(data.getName())) {
            warningMessage.append("请填写设备型号！\r\n");
        } else {
            VwEqu equ = accountingInfoDao.getVwEquByName(data.getName());
            if (equ == null) {
                warningMessage.append("设备型号不存在，请填写存在的设备型号，如不清楚请咨询类似项目机加工艺卡相关制作人！\r\n");
            }
        }

        if (data.getWorkHoursStr() != null && !data.getWorkHoursStr().equals("")) {
            data.setWorkHoursStr(data.getWorkHoursStr().replace("\r", "").replace("\n", "").trim());
        }
        if (data.getWorkHoursStr() == null) {
            warningMessage.append("请填写工时（小时）！\r\n");
        } else if ("".equals(data.getWorkHoursStr())) {
            warningMessage.append("请填写工时（小时）！\r\n");
        } else {
            try {
                BigDecimal workHours = new BigDecimal(data.getWorkHoursStr());
                //小于等于-1
                if (workHours.compareTo(new BigDecimal(-1)) < 1) {
                    warningMessage.append("工时（小时）不正确！请修改正确后重新导入！正确的工时（小时）应该是非负正整数。\r\n");
                }else if(data.getWorkHoursStr().contains(".")){
                    warningMessage.append("工时（小时）不正确！请修改正确后重新导入！正确的工时（小时）应该是正整数。\r\n");
                }
            } catch (Exception e) {
                warningMessage.append("工时（小时）不正确！请修改正确后重新导入！正确的工时（小时）应该是非负正整数。\r\n");
            }
        }
        if (data.getWorkMinuteStr() == null) {
            warningMessage.append("请填写工时（分钟）！\r\n");
        } else if ("".equals(data.getWorkMinuteStr())) {
            warningMessage.append("请填写工时（分钟）！\r\n");
        } else {
            try {
                BigDecimal workMinute = new BigDecimal(data.getWorkMinuteStr());
                //小于等于-1
                if (workMinute.compareTo(new BigDecimal(-1)) < 1) {
                    warningMessage.append("工时（分钟）不正确！请修改正确后重新导入！正确的工时（分钟）应该是非负正整数,并且大于等于0小于等于59。\r\n");
                }else if (workMinute.compareTo(new BigDecimal(59))==1) {
                    warningMessage.append("工时（分钟）不正确！请修改正确后重新导入！正确的工时（分钟）应该是非负正整数,并且大于等于0小于等于59。\r\n");
                }else if(data.getWorkMinuteStr().contains(".")){
                    warningMessage.append("工时（分钟）不正确！请修改正确后重新导入！正确的工时（分钟）应该是正整数,并且大于等于0小于等于59。\r\n");
                }
            } catch (Exception e) {
                warningMessage.append("工时（分钟）不正确！请修改正确后重新导入！正确的工时（分钟）应该是非负正整数,并且大于等于0小于等于59。\r\n");
            }
        }
        if (warningMessage == null || warningMessage.toString().length() == 0) {
            data.setBatId(param.getBatId());
            data.setMajor(param.getMajor());
            data.setPart(param.getPart());
            data.setType(2);
            data.setDataUseType(order.getTaskType());
            data.setProCode(param.getProCode());
            data.setGetDate(currentTime);
            data.setGetUid(ShiroUtils.getUserId());
            data.setIsEffectiveFlag(1);
            data.setCostId(cost.getId());
            data.setIsPrototypeDataFlag(0);
            BusBudgetAccountingBasicInfoConfigModel condition = new BusBudgetAccountingBasicInfoConfigModel();
            condition.setBatId(order.getId());
            condition.setCode("Machining quota");
            BusBudgetAccountingBasicInfoConfigModel quotaConfigModel = accountingInfoDao.getBusBudgetAccountingBasicInfoConfigByBatIdAndCode(condition);
            data.setBmeVersion(quotaConfigModel.getValue());
            data.setHours(new BigDecimal(data.getWorkHoursStr()).add(new BigDecimal(data.getWorkMinuteStr()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP)));
            macList.add(modelConvert(data));
        } else {
            data.setWarnInfo(warningMessage.toString());
            errorList.add(data);
        }
    }

    /**
     * 持久化
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (errorList.size() > 0) {
            callBack.onWarning(errorList);
        } else if (macList.size() > 0) {
            BusBudgetAccountingCost cost = accountingInfoDao.getBusBudgetAccountingCostByPrimaryKey(param.getId());
            accountingInfoDao.updateBusMachiningHoursToInvalid(cost.getId());
            for (int i = 0; i < macList.size(); i++) {
                accountingInfoDao.insertBusMachiningHours(macList.get(i));
            }
            cost.setDataSource("1");
            accountingInfoDao.updateBusBudgetAccountingCostDataSourceByPrimaryKey(cost);
            callBack.onSuccess();
        }
    }

    /**
     * 异常处理
     *
     * @param exception 异常信息
     * @param context
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {

    }

    /**
     * rawMatModelToBusMaterialData 模型转换类
     *
     * @param
     * @return com.zhongwang.business.gen.entity.BusMaterialData
     * @throws
     * @author 徐一贺
     * @date 2020/11/21 15:09
     */
    private BusMachiningHours modelConvert(MacHoursExportModel source) {
        BusMachiningHours busMachiningHours = new BusMachiningHours();
        busMachiningHours.setId(source.getId());
        busMachiningHours.setBatId(source.getBatId());
        busMachiningHours.setProCode(source.getProCode());
        busMachiningHours.setDiagram(source.getDiagram());
        busMachiningHours.setDrawingNo(source.getDrawingNo());
        busMachiningHours.setNum(new BigDecimal(source.getNum()));
        busMachiningHours.setRemark(source.getRemark());
        busMachiningHours.setDataUseType(source.getDataUseType());
        busMachiningHours.setType(source.getType());
        busMachiningHours.setMajor(source.getMajor());
        busMachiningHours.setProcess(source.getProcess());
        busMachiningHours.setSourceProCode(source.getSourceProCode());
        busMachiningHours.setPart(source.getPart());
        busMachiningHours.setSourcePart(source.getSourcePart());
        busMachiningHours.setDsId(source.getDsId());
        busMachiningHours.setGetDate(source.getGetDate());
        busMachiningHours.setGetUid(source.getGetUid());
        busMachiningHours.setBmeCode(source.getBmeCode());
        busMachiningHours.setName(source.getName());
        busMachiningHours.setHours(source.getHours());
        busMachiningHours.setBmeVersion(source.getBmeVersion());
        busMachiningHours.setPostName(source.getPostName());
        busMachiningHours.setPostTel(source.getPostTel());
        busMachiningHours.setPostDept(source.getPostDept());
        busMachiningHours.setIsEffectiveFlag(source.getIsEffectiveFlag());
        busMachiningHours.setCostId(source.getCostId());
        busMachiningHours.setIsPrototypeDataFlag(source.getIsPrototypeDataFlag());
        return busMachiningHours;
    }
}
